<?php


namespace app\admin\controller\goods;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

class Exchange extends Backend
{
    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Exchange
     */
    protected $model = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Exchange;

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('type',2)
                ->order($sort, $order)
                ->paginate($limit)->each(function($item,$key){
                    $cate_title = Db::name('cate_goods')->where('id',$item['cate_pid'])->field('pid,title')->find();
                    if(!empty($item['cate_id']))
                    {
                        $cate_name     = Db::name('cate_goods')->where('id',$item['cate_id'])->value('title');
                        $item['title'] = $cate_title['title']. ' L__ ' . $cate_name;
                    }else{
                        $item['title'] = isset($cate_title['title']) ? $cate_title['title'] : "";
                    }
                    switch($item['status'])
                    {
                        case 1;
                            $item['status'] = '是';
                            break;
                        case 2;
                            $item['status'] = '否';
                            break;
                    }
                    return $item;
                });

            foreach ($list as $row) {
                $row->visible(['id','name','cate_id','image','num','money','status','title','create_time']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $data['name']      = $params['row']['name'];
                $data['image']     = $params['row']['image'];
//                $data['num']       = $params['row']['num'];
                $data['item']      = $params['row']['basic'];
                $data['desc']      = $params['row']['desc'];
                $data['cate_pid']  = $params['cate_id'];
                $data['cate_id']   = $params['cate_ids'];
                $data['type']      = 2;// 爱心值商品
                $data['create_time']  = time();

                if(!$data['name'])    $this->error(__('请输入商品名称'));
                if(!$data['cate_pid'])$this->error(__('请选择商品分类'));

                $item = json_decode($data['item'],true);
                if(!$item)$this->error(__('请填写规格'));

                foreach($item as $val)
                {
                    if(!$val['title'] || !$val['stock'] || !$val['integral'])
                        $this->error(__('规格不能为空'));
                }

                $res = Db::name('goods')->insert($data);
                if($res)
                {
                    $this->success();
                }else{
                    $this->error(__('添加失败'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

//        $this->view->assign('cate',Db::name('cate_goods')->where(['pid'=>['>',0]])->field('id,title')->select());
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $goods = $this->request->post("");
                if ($params) {
                    $data['name'] = $params['name'];
                    $data['image'] = $params['image'];
                    $data['item'] = $params['basic'];
                    $data['desc'] = $params['desc'];
                    $data['status'] = $params['status'];
//                    $data['pool'] = $params['pool'];
                    $data['create_time'] = time();
                    $data['cate_pid'] = $goods['row']['cate_id'];
                    $data['cate_id'] = $goods['row']['cate_ids'];

                    $item = json_decode($data['item'], true);
                    if (count($item) == 0) $this->error(__('请输入规格'));

                    foreach ($item as $val) {
                        if (!$val['title'] || !$val['stock'] || !$val['integral'])
                            $this->error(__('规格不能为空'));
                    }


                    $res = Db::name('goods')->where('id', $params['id'])->update($data);
                    if ($res) {
                        $this->success();
                    } else {
                        $this->error(__('修改失败'));
                    }
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['cate_id'])
        {
            $cates = Db::name('cate_goods')->where('id',$row['cate_id'])->field('id,title')->find();
        }else{
            $cates = "";
        }

        $this->view->assign('cate',Db::name('cate_goods')->where(['pid'=>['=',0]])->field('id,title')->select());
        $this->view->assign('cates',$cates);
        $this->view->assign("row", $row);
        $this->view->assign('item',$row['item']);
        return $this->view->fetch();
    }



    /*
     * 获取添加到爱心值商品中
     * */
    public function inAdd()
    {
        $ids = array_unique($this->request->param());
        // 转成字符串
        $ids = implode(',',array_unique($ids));
        $res = Db::name('goods')->where('id','in',$ids)->update(['type'=>2]);
        if($res)
        {
            $this->success();
        }else{
            $this->error(__('添加失败'));
        }
    }



}